package Judge.Login.Model;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import Packet.Packet;
import Packet.PacketFactory;
import Packet.PacketType;
import Exception.LoginFailureException;

import Core.Model.*;

class ServerConnection 
{
	public ServerConnection(Socket socket, ClientType type) 
	{
		this.socket = socket;
		this.type = type;
		System.out.println("IP" + socket.getInetAddress());
	}

	public boolean login(String userName, String password)  throws LoginFailureException
	{
		Packet packet = new PacketFactory().makeClientLoginPacket(PacketFactory.sourceId, PacketFactory.destinationId,
				userName, password, this.type);
		//System.out.println("packet : " + packet.toString());
		try
		{
			ObjectOutputStream oos = new ObjectOutputStream(new DataOutputStream(socket.getOutputStream()));
			ObjectInputStream ois = new ObjectInputStream(new DataInputStream(socket.getInputStream()));
			//System.out.println("sendPacket : " + packet);
			oos.writeObject(packet);
			oos.flush();
			
			try
			{
			    Packet receivePacket = (Packet)ois.readObject();
			    System.out.println("Team receive Packet : " + receivePacket);
			    if (receivePacket.getPacketType() == PacketType.ClientLoginSucessfulPacket)
				{
					return true;
				}
				else if (receivePacket.getPacketType() == PacketType.ClientLoginNoAccountPacket)
				{
					throw new LoginFailureException("No Such Account");
				}
				else if (receivePacket.getPacketType() == PacketType.ClientLoginPasswordErrorPacket)
				{
					throw new LoginFailureException("Password Error");
				}
			}
			catch(ClassNotFoundException e)
			{
				System.out.println("ClassNotFoundException e");
				return false;
			}
		}
		catch (IOException e) 
		{
			System.out.println("IOException e");
		}
		return true;
	}
	
	private Socket socket;
	private ClientType type;
}
